//
//  UIButtion+CountDown.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/4.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit

extension UIButton {
    func startWithTime(_ timeLine: Int, title: String, countDownTitle: String, mainColor: UIColor, countColor: UIColor) {
        var timeOut = timeLine
        let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.global())
        
        timer.setEventHandler {
            if timeOut <= 0 {
                timer.cancel()
                DispatchQueue.main.async {
                    self.backgroundColor = mainColor
                    self.setTitle(title, for: .normal)
                    self.isUserInteractionEnabled = true
                }
            }
            else {
                DispatchQueue.main.async {
                    self.backgroundColor = countColor
                    self.setTitle("\(countDownTitle)(\(timeOut))", for: .normal)
                    self.isUserInteractionEnabled = false
                }
                timeOut -= 1
            }
        }
        timer.scheduleRepeating(deadline: .now(), interval: .seconds(1))
        timer.resume()

    }
}
